package me.chyxion.jdbc.pagination;

import java.util.Collection;
import me.chyxion.jdbc.Order;
import lombok.extern.slf4j.Slf4j;
import me.chyxion.jdbc.SqlAndArgs;
import java.util.stream.Collectors;
import me.chyxion.jdbc.util.StringUtils;

/**
 * @version 0.0.1
 * @since 0.0.1
 * @author Shaun Chyxion <br>
 * chyxion@163.com <br>
 * Dec 10, 2015 10:15:52 PM
 */
@Slf4j
public class MySQLCompatiblePaginationProcessor implements PaginationProcessor {

	/**
	 * {@inheritDoc}
	 */
	@Override
	public SqlAndArgs process(final Collection<Order> orders,
							  final int start,
							  final int limit,
							  String sql,
							  final Collection<? super Object> args) {
		log.info("Process MySQL Compatible Pagination Sql [{}].", sql);

		sql += " order by " + StringUtils.join(
				orders.stream().map(Object::toString)
						.collect(Collectors.toList()), ", ") + " limit ?";
		args.add(start);
		if (limit > 0) {
			sql += ", ?";
			args.add(limit);
		}
		log.info("Process Pagination Sql Result [{}].", sql);
		return new SqlAndArgs(sql, args);
	}
}
